<!-- 选项-component -->
<template>
  <li
    @click="handleClick"
    class="flex items-center justify-between lg:py-3.5 py-4 px-5 group cursor-pointer hover:text-theme-color hover:bg-light-background dark:hover:bg-4x-dark-foreground"
  >
    <div class="flex items-center">
      <div class="mr-4">
        <i :class="`pi pi-${curType}`" />
      </div>
      <b class="group-hover-text-theme text-sm font-bold">{{
        i18nStore.translate(curContent)
      }}</b>
    </div>
    <div class="ml-2" v-if="curIcon.type">
      <i
        class="vue-feather group-hover-text-theme opacity-50 feather feather-arrow-down"
        :class="`pi pi-${curIcon.type}`"
        style="font-size: 12px"
      />
    </div>
  </li>
  <!-- toast -->
  <Toast position="right" group="formEditToast" />
  <Dialog
    v-model:visible="visible"
    modal
    :header="i18nStore.translate('your_directory_name')"
    class="w-full pc:w-[35rem]"
  >
    <div class="flex my-2 mobile:w-full" v-if="typeS === 2">
      <div class="relative w-16 shrink-0">
        <div
          v-if="fileStore.curFileInfo.type === 'folder'"
          class="svg-color-theme"
        >
          <SvgIcon
            name="folder"
            :style="{ width: '53px', height: '52px' }"
            iconClass="svg-color-theme"
          />
        </div>
        <div
          v-else-if="fileStore.curFileInfo.type === 'image'"
          class="relative w-16 shrink-0"
        >
          <img
            :src="fileStore.curFileInfo.url"
            alt=""
            class="ml-0.5 h-12 w-12 rounded object-cover"
          />
        </div>
        <div
          v-else-if="fileStore.curFileInfo.type === 'video'"
          class="relative w-16 shrink-0"
        >
          <video
            :src="fileStore.curFileInfo.url"
            class="ml-0.5 h-12 w-12 object-cover rounded"
            loop
            muted
            @loadeddata="
              (e) => {
                e.target.volume = 0;
                e.target.play();
              }
            "
          />
        </div>
        <div v-else class="flex items-center justify-center pr-2">
          <span
            class="text-theme-color absolute z-[5] mx-auto mt-1 inline-block w-7 overflow-hidden text-ellipsis text-center text-[9px] font-semibold"
          >
            {{ fileStore.curFileInfo.type }}
          </span>
          <SvgIcon
            name="file"
            svgClass="vue-feather dark:text-gray-800 text-gray-100 "
            :style="{ width: '38px', height: '51px' }"
            iconClass="svg-color-theme"
          />
        </div>
      </div>
      <div>
        <p>{{ fileStore.curFileInfo.name }}</p>
        <div class="text-center relative">
          <div class="flex items-center justify-center">
            <small class="flex gap-2 text-xs text-gray-500 dark:text-gray-500">
              <i
                class="pi pi-link vue-feather text-theme-color text-xs"
                v-if="fileStore.curFileInfo.isShare"
              />
              <i v-if="!fileStore.curFileInfo.isFolder">{{
                fileStore.curFileInfo.size
              }}</i>
              <span
                class="text-xs text-gray-500 dark:text-gray-500 lg:inline-block"
                >{{
                  i18nStore.translate('date', fileStore.curFileInfo.createTime)
                }}</span
              >
            </small>
          </div>
        </div>
      </div>
    </div>
    <div class="flex flex-col gap-3 mb-3 pb-10 mobile:w-full">
      <label for="username" class="font-semibold w-6rem">{{
        i18nStore.translate('please_enter_a_file_name')
      }}</label>
      <InputText
        id="username"
        class="flex-auto h-10 font-semibold w-6rem text-xl"
        autocomplete="off"
        v-model="filesname"
      />
    </div>
    <div
      class="absolute bottom-0 left-0 right-0 flex items-center space-x-4 px-6 py-4 pb-6 md:relative"
    >
      <button
        @click="close"
        type="button"
        class="button-base w-full secondary hover:opacity-70 hover:scale-110 dark:text-[#00e1ff]"
      >
        <div class="content">{{ i18nStore.translate('close') }}</div>
      </button>
      <button
        type="button"
        class="button-base w-full theme hover:opacity-70 hover:scale-110"
        @click="addFiles"
        v-if="typeS === 1"
      >
        {{ i18nStore.translate('confirm') }}
      </button>
      <button
        type="button"
        class="button-base w-full theme hover:opacity-70 hover:scale-110"
        @click="editFiles"
        v-if="typeS === 2"
      >
        {{ i18nStore.translate('confirm') }}
      </button>
    </div>
  </Dialog>
</template>

<script setup>
import {
  useFlagStore,
  useI18nStore,
  useFileStore,
  useToastStore,
  useUserInfoStore,
  SORT_ORDER,
  SORT_TYPE
} from '@/stores';
import { uploadBigFolder } from '@/apis/upload';
import { addFolder, renameFile } from '@/apis/file';
import Toast from 'primevue/toast';
import { refreshUserInfo } from '@/router';
const flagStore = useFlagStore();
const i18nStore = useI18nStore();
const fileStore = useFileStore();
const toastStore = useToastStore();
const userInfoStore = useUserInfoStore();

const props = defineProps({
  option: {
    type: Object,
    default: () => {}
  }
});
const curType = ref('');
const curContent = ref('');
const curIcon = ref({});
const emit = defineEmits(['close']);
const visible = ref(false);
const typeS = ref(1);
const filesname = ref('');

// 初始化
onMounted(() => {
  curType.value = props.option.type;
  curContent.value = props.option.content;
  if (props.option.icon) {
    curIcon.value = props.option.icon;
  }
});

// 单个文件上传触发
const uploadFiles = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.multiple = false;
  input.onchange = () => {
    fileStore.onUploader(input.files[0]);
    input.remove();
  };
  input.click();
};
// 上传文件夹并校验大小
const uploadWholeFolder = () => {
  const input = document.createElement('input');
  input.type = 'file';
  input.webkitdirectory = true;
  input.onchange = async () => {
    const files = Array.from(input.files);
    let filesSize = 0;
    for (let i = 0; i < files.length; i++) {
      filesSize += files[i].size;
    }
    const nowSize =
      userInfoStore.userInfo.fileWalletDTO.storageAmount -
      userInfoStore.userInfo.fileWalletDTO.storageUsed;
    if (filesSize > nowSize) {
      toastStore.showToast({
        severity: 'error',
        summary: i18nStore.translate(
          'insufficient_remaining_storage_space_please_upgrade_package_or_purchase_space'
        ),
        detail: '',
        life: 2000,
        group: 'upload_success'
      });
      return;
    } else {
      uploadBigFolder(files);
    }
    input.remove();
  };
  input.click();
};

const addFiles = () => {
  if (!filesname.value) return;
  let filePath = '';
  if (fileStore.getPath() === '/') {
    filePath = filesname.value + '/';
  } else {
    filePath = fileStore.getPath() + filesname.value + '/';
  }
  addFolder({
    filePath
  }).then(() => {
    emit('close');
    fileStore.updateFileList();
  });
  visible.value = false;
  filesname.value = '';
};

const editFiles = () => {
  let newName = filesname.value;
  if (!props.option.file.isFolder) {
    const ext = props.option.file.name.split('.').pop();
    newName = filesname.value + '.' + ext;
  }
  renameFile({
    id: parseInt(props.option.file.id),
    newName
  }).then(() => {
    emit('close');
    fileStore.updateFileList();
  });
  visible.value = false;
  filesname.value = '';
};

const close = () => {
  emit('close');
  visible.value = false;
  filesname.value = '';
};
// 选项类型配置
const typeConfig = {
  // 列表视图
  list: 'list',
  // 网格视图
  grid: 'th-large',
  // 日期排序
  date: 'calendar',
  // 名称排序
  name: 'language',
  // 删除
  delete: 'trash',
  // 上传文件
  upload_file: 'upload',
  // 上传整个文件夹
  upload_folder: 'cloud-upload',
  // 新建文件夹
  add_folder: 'folder-open',
  // 编辑名称
  edit_name: 'file-import',
  // 分享
  share: 'link',
  // 细节
  detail: 'eye',
  // 下载
  download: 'cloud-download',
  //恢复
  recovery: 'map',
  // 彻底删除
  delete_forever: 'times-circle',
  // 复制
  copy: 'copy',
  // 二维码
  camera: 'camera',
  // 电子邮件分享
  send: 'send',
  // 文件迁出
  reply: 'reply'
};

watch(
  () => [fileStore.curSortType, fileStore.curSortOrder],
  () => {
    switch (curType.value) {
      case typeConfig.date:
        if (fileStore.curSortType === SORT_TYPE.DATE) {
          if (fileStore.curSortOrder === SORT_ORDER.ASC) {
            curIcon.value = { type: 'arrow-up' };
          } else {
            curIcon.value = { type: 'arrow-down' };
          }
        } else {
          curIcon.value = {};
        }
        break;
      case typeConfig.name:
        if (fileStore.curSortType === SORT_TYPE.FILE_NAME) {
          if (fileStore.curSortOrder === SORT_ORDER.ASC) {
            curIcon.value = { type: 'arrow-up' };
          } else {
            curIcon.value = { type: 'arrow-down' };
          }
        } else {
          curIcon.value = {};
        }
        break;

      default:
        break;
    }
  }
);
const handleClick = () => {
  switch (curType.value) {
    case typeConfig.list:
      // 切换为列表视图
      fileStore.toggleGridironPlan(false);
      curType.value = typeConfig.grid;
      curContent.value = 'grid_view';
      break;
    case typeConfig.grid:
      // 切换为网格视图
      fileStore.toggleGridironPlan(true);
      curType.value = typeConfig.list;
      curContent.value = 'list_view';
      break;
    case typeConfig.date:
      // 根据日期切换排序
      if (fileStore.curSortOrder === SORT_ORDER.ASC) {
        fileStore.switchSortFunc(SORT_TYPE.DATE, SORT_ORDER.DESC);
      } else if (fileStore.curSortOrder === SORT_ORDER.DESC) {
        fileStore.switchSortFunc(SORT_TYPE.DATE, SORT_ORDER.ASC);
      } else {
        fileStore.switchSortFunc(SORT_TYPE.DATE, SORT_ORDER.ASC);
      }
      break;
    case typeConfig.name:
      // 根据名称切换排序
      if (fileStore.curSortOrder === SORT_ORDER.ASC) {
        fileStore.switchSortFunc(SORT_TYPE.FILE_NAME, SORT_ORDER.DESC);
      } else if (fileStore.curSortOrder === SORT_ORDER.DESC) {
        fileStore.switchSortFunc(SORT_TYPE.FILE_NAME, SORT_ORDER.ASC);
      } else {
        fileStore.switchSortFunc(SORT_TYPE.FILE_NAME, SORT_ORDER.ASC);
      }
      break;
    case typeConfig.delete:
      // 删除文件或文件夹
      if (props.option.file) {
        fileStore.deleteFile(props.option.file, 1).then(() => {
          curType.value = typeConfig.delete;
          emit('close');
          refreshUserInfo();
        });
        curType.value = 'spin pi-spinner';
      }
      break;
    case typeConfig.upload_file:
      // 上传文件
      uploadFiles(fileStore.curFolderId);
      emit('close');
      break;
    case typeConfig.add_folder:
      // 新建文件夹
      typeS.value = 1;
      visible.value = true;
      break;
    case typeConfig.edit_name:
      // 修改文件名
      typeS.value = 2;
      visible.value = true;
      filesname.value = props.option.file.isFolder
        ? props.option.file.name
        : props.option.file.name.split('.').slice(0, -1).join('.');
      break;
    case typeConfig.upload_folder:
      // 上传整个文件夹
      uploadWholeFolder();
      emit('close');
      break;
    case typeConfig.share:
      // 分享
      flagStore.setShareBoardOpen(true);
      emit('close');
      break;
    case typeConfig.detail:
      // 查看详情
      emit('close');
      nextTick(() => {
        flagStore.setInfoBoardOpen(true);
      });
      break;
    case typeConfig.download:
      console.log(123);

      fileStore.downloadFile(fileStore.curFileInfo);
      curType.value = 'spin pi-spinner';
      setTimeout(() => {
        emit('close');
      }, 1000);
      break;
    case typeConfig.recovery:
      fileStore.recoverFileMove(props.option.file.id).then(() => {
        curType.value = typeConfig.recovery;
        refreshUserInfo();
        emit('close');
      });
      curType.value = 'spin pi-spinner';
      break;
    case typeConfig.delete_forever:
      fileStore.deleteFileMove(props.option.file.id).then(() => {
        curType.value = typeConfig.delete;
        emit('close');
      });
      curType.value = 'spin pi-spinner';
      break;
    case typeConfig.copy:
      const url = createShareLink(
        fileStore.curFileInfo.shareId,
        fileStore.curFileInfo.isSmall
      );
      // 复制链接
      const el = document.createElement('textarea');
      el.value = url;
      document.body.appendChild(el);
      el.select();
      document.execCommand('copy');
      document.body.removeChild(el);
      emit('close');
      break;
    case typeConfig.camera:
      flagStore.setQrcodeVisible(true);
      emit('close');
      break;
    case typeConfig.send:
      flagStore.setEmailVisible(true);
      emit('close');
      break;
    case typeConfig.reply:
      showTreePopup({ ...fileStore.curFileInfo, isMove: 1 });
      emit('close');
      break;
    default:
      break;
  }
};
const createShareLink = (shareId, Small) => {
  const id = btoa(`${shareId}`);
  const isSmall = btoa(`${Small}`);
  return `https://okpan.fun/share/${id}/post/${isSmall}`;
};
</script>

<style scoped lang="scss">
@import './index.scss';
</style>
